define(['config', 'text!app/module/system/materialRecordManage.html', 'laypage',
    'mydialog', 'autocomplete', 'jqGrid', 'common', 'laydate'
], function (config, viewHTML, laypage,
             mydialog, autocomplete, jqGrid, common, laydate) {

    var token = (cache.go("token") === 'undefined') ? 'none' : cache.go("token");

    var grid_url = "/api/goods";

    var model = avalon.define({
        $id: "material",
        materialInfo: {
        	id:"",
			name:"",
			model:"",
			typeId:"",
			floorPrice:"",
			describes:"",
			remarks:"",
			item:"",
			createUser:"",
			createTime:""
        },
        // 查询条件
        query: {
            name: "",
        },
        flag:true,
        arsUnit: [
            {
                key: "件",
                val: '011'
            }
        ],
        type: [
            {
                key: "请选择",
                val: ""
            },
            {
                key: "成品",
                val: "CP"
            }, {
                key: "原料",
                val: "YL"
            }, {
                key: "辅料",
                val: "FL"
            }
        ],
        arsType: [
            {
                key: "成品",
                val: "CP"
            }, {
                key: "原料",
                val: "YL"
            }, {
                key: "辅料",
                val: "FL"
            }
        ],
        init: function () {
            model.loadGrid();
            model.addEvent();
        },
        loadGrid: function () {
            function t(val, opt, row) {
                var html_con = '<div class="operating" data-id="' + row.id + '"><span class="fa fa-edit mrb" title="修改"><a href="javascript:void();" ms-click="edit(el)"/></span><span class="fa fa-trash-o mrb" title="删除"></span>' + (row.is_deleted == 1 ? '<span class="fa fa-reply mrb" title="恢复"></span>' : '') + '</div>';
                return html_con;
            }


            var i = Public.setGrid();
            $("#grid").jqGrid({
                loadBeforeSend: function (jqXHR) {
                    jqXHR.setRequestHeader("X-AuthToken", token);
                },
                datatype: "json",
                mtype: "POST",
                url: grid_url + "/list",
                postData: model.query.$model,
                loadComplete: function (data) {
                	console.log("11111111111111111111111111",data);
                    if(!data.success){
                        alert(data.msg);
                    }
                },
                colModel:[{
					name: "operation",
					label: "操作",
					formatter: t,
					align: "center",
					width: '60px',
					title: false
				},
				{
					name: "id",
					label: "ID",
					align: "center",
					width: '50px',
					title: false,
					hidden:true
				},
				{
					name: "name",
					label: "设备名称",
					align: "center",
					width: '66px',
					title: false
				},
				{
					name: "model",
					label: "规格",
					align: "center",
					width: '66px',
					title: false
				},
				{
					name: "typeId",
					label: "类型id",
					align: "center",
					width: '66px',
					title: false,
					hidden:true
				},
				{
					name: "floorPrice",
					label: "单价",
					align: "center",
					width: '66px',
					title: false
				},
				{
					name: "retailprice",
					label: "建议零售价",
					align: "center",
					width: '66px',
					title: false
				},
				{
					name: "describes",
					label: "描述",
					align: "center",
					width: '66px',
					title: false
				},
				{
					name: "remarks",
					label: "备注",
					align: "center",
					width: '66px',
					title: false
				}
			],
                cmTemplate: {
                    sortable: false,
                    title: false,
                    align: "center"
                },
                //分页
                page: 1,
                rowNum: 10,
                rowList: [10, 20, 30],
                height: i.h,
                autowidth: true,
                pager: '#page',
                sortname: 'id',
                viewrecords: true,
                forceFit: false,
                rownumbers: true,
                multiselect: true,
                multiboxonly: true,
                sortorder: "desc",
                jsonReader: {
                    root: "data.list",
                    records: "data.totalRow",
                    total: "data.totalPage",
                    repeatitems: false,
                    id: "id"
                },loadError: function (xhr, status, error) {
                    alert(JSON.parse(xhr.responseText).msg);
                }
            })
        },
        reset: function () {
            model.query = {
                name: "",
                type:""
            };
            model.type =  [
                {
                    key: "请选择",
                    val: ""
                },
                {
                    key: "成品",
                    val: "CP"
                }, {
                    key: "原料",
                    val: "YL"
                }, {
                    key: "辅料",
                    val: "FL"
                }
            ];
            model.queryData();
        },
        queryData: function () {
            console.log(model.query.type)
            $("#grid").jqGrid("setGridParam", {
                url: grid_url + "/list",
                datatype: "json",
                mtype: 'POST',
                page: 1,
                postData: model.query.$model
            }).trigger("reloadGrid");
        },


        //添加或更新
        edit: function (materialInfo, id) {
            var url = "/api/goods/save";
            model.arsUnit = [
                {
                    key: "件",
                    val: "011"
                }
            ];
            model.arsType = [
                {
                    key: "成品",
                    val: "CP"
                }, {
                    key: "原料",
                    val: "YL"
                }, {
                    key: "辅料",
                    val: "FL"
                }
            ];
            if (materialInfo === -1) {
                model.initmaterial();
            } else {
                // 修改用户
                model.materialInfo = materialInfo;
                model.materialInfo.id = id;
                if (model.materialInfo.type == "原料") {
                    model.materialInfo.type = "YL";
                } else if (model.materialInfo.type == "成品") {
                    model.materialInfo.type = "CP";
                } else if (model.materialInfo.type == "辅料") {
                    model.materialInfo.type = "FL";
                }
                if (model.materialInfo.unit == "件") {
                    model.materialInfo.unit = "011";
                }
            }
            dialog({
                title: '编辑商品信息',
                content: $('#editUser'),
                okValue: "确定",
                ok: function () {
                    console.log(model.materialInfo.type);
                    // 提交修改
                     if(model.isEmpty(model.materialInfo.name.trim(),"品名不能为空!")){
                         $.ajax({
                             type: "POST",
                             url: url,
                             contentType: "application/json",
                             data: JSON.stringify(model.materialInfo),
                             beforeSend: function (xhr) {
                                 xhr.setRequestHeader("X-AuthToken", token);
                             },
                             success: function (data, status, xhr) {
                                 if(data.success){
                                     model.queryData();
                                 }else {
                                     parent.Public.tips({
                                         type: 2,
                                         content: res.getMessage()
                                     })
                                 }
                             },
                             error: function (responseData, textStatus, errorThrown) {
                                 alert("系统异常");
                             }
                         });
                     }else {
                         return false;
                     }
                },
                cancelValue: "取消",
                cancel: function () {
                }
            }).showModal();
        },
        del: function (ids) {
            dialog({
                title: "确认操作",
                content: "确定删除？ 此操作不可恢复！",
                okValue: "确定",
                ok: function () {
                    $.ajax({
                        type: "POST",
                        url: "/api/goods/delete",
                        data: {
                            "ids": ids
                        },
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("X-AuthToken", token);
                        },
                        success: function (data, status, xhr) {
                            if (data) {
                                $('#grid').jqGrid('delRowData', ids);
                            }
                            model.queryData();
                        },
                        error: function (responseData, textStatus, errorThrown) {
                            alert("Failed: " + JSON.stringify(responseData));
                        }

                    });

                },
                cancelValue: "取消",
                cancel: function () {
                }
            }).showModal();
        },
        addEvent: function () {
            $(".grid-wrap").on("click", ".fa-edit", function (e) {
                var t = $(this).parent().data("id");
                model.edit($("#grid").getRowData(t), t);
            });
            // 删除
            $(".grid-wrap").on("click", ".fa-trash-o", function (t) {
                var ei = [];
                var e = $(this).parent().data("id");
                ei.push(e);
                model.del(e);
            });
            $("#search").click(function (e) {
                e.preventDefault();
                model.queryData();
            });
            $(".fa-refresh").click(function (e) {
                e.preventDefault();
                model.reset();
                model.queryData();
            })
            //编辑用户信息
            $(".grid-wrap").on("click", ".userManage", function (e) {
                var id = $("#grid").jqGrid('getGridParam', 'selrow'),
                    userId = $("#grid").jqGrid("getRowData", id).userId;
                model.editUser(userId);
            })
            $(".grid-wrap").on("click", ".userRole", function (e) {
                var id = $("#grid").jqGrid('getGridParam', 'selrow'),
                    userId = $("#grid").jqGrid("getRowData", id).userId;
                model.editUserRole(userId);
            })

//             $("#aadddd").click(function (t) {
//                 model.edit(-1);
//             });
            $("#btn-batchDel").click(function (e) {
                e.preventDefault();
                // if (Business.verifyRight("BU_DELETE")) {
                var t = $("#grid").jqGrid("getGridParam", "selarrrow");
                t.length ? model.del(t.join()) : parent.Public.tips({
                    type: 2,
                    content: "请选择需要删除的项"
                })
                // }
            });
        },
        initmaterial: function () {
            model.materialInfo = {
            		id:"",
					name:"",
					model:"",
					typeId:"",
					floorPrice:"",
					describes:"",
					remarks:"",
					item:"",
					createUser:"",
					createTime:""

            }
        },
        isEmpty: function (value, alerttxt) {
                if (value == null || value == "") {
                    Public.tips({
                            type: 2,
                            content: alerttxt
                        });
                     return false;
                }
                else {
                    return true;
                }
        }
    });

    // 定义视图模块
    var viewmod = {
        viewtSrc: viewHTML,
        viewInit: function () {
            model.init();
        }, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
        viewDestroy: function () {
        } // 切换菜单时销毁原来的view
    };
    return viewmod;


});
